<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索框与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="clearChange">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表信息区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 状态开关切换区域 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" 
                       icon="el-icon-edit" 
                       circle
                       @click="showEditDialog(scope.row.id)">
            </el-button>
            <!-- 删除按钮 -->
            <el-button @click="deleteList(scope.row.id)" type="danger" icon="el-icon-delete" circle></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting" 
                         circle
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
            <!-- {{scope.row.id}} -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog @close="addDialogClosed" 
               title="添加用户" 
               :visible.sync="addDialogVisible" 
               width="50%">
      <!-- 主体内容区域 -->
      <el-form :model="addForm" 
               :rules="addFormRules" 
               ref="addFormRef" 
               label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" 
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

     <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" 
               :visible.sync="editDialogVisible" 
               width="50%"
               @close="editDialogClosed">
      <!-- 主体内容区域 -->
      <el-form :model="editForm" 
               :rules="editFormRules" 
               ref="editFormRef" 
               label-width="70px ">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">
          取 消
        </el-button>
     
        <el-button type="primary" 
        @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesdialogVisible"
      width="30%"
      @close="setRoleClosed">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <!-- 分配新角色选择下拉框区域 -->
          <el-select placeholder="请选择"  v-model="roleValue">
            <el-option
              v-for="item in roleInfo"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setNewRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的正则表达式
    var checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(reg.test(value)){
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的正则表达式
    var checkPhone = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号码格式不正确'))
      }
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      
      // 添加用户表单的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 查询到的用户信息的数据
      editForm: {},
      // 添加用户表达单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur'}
        ]
      },

       // 修改用户表达单的验证规则对象
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur'}
        ]
      },
      // 分配角色显示对话框
      setRolesdialogVisible:false,
      // 需要被分配角色的用户信息
      userInfo:{},
      // 系统角色信息
      roleInfo:[],
      // 分配新角色选择下拉框的当前值
      roleValue:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 监听pagesize改变的事件
    handleSizeChange(newsize) {
      // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 监听switch状态改变
    async userStatusChanged(userInfo) {
      // console.log(statuserInfou)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听清空搜索框
    clearChange() {
      this.getUserList()
    },
    // 监听添加用户对话框关闭
    addDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    //点击确定按钮添加新用户
    addUser(){
      this.$refs.addFormRef.validate(async valid => {
        //校验失败
        if(!valid) return this.$message.error('请检查信息！')
        //可以发起添加用户的网络请求
        const {data:res} = await this.$http.post('users', this.addForm)
        if(res.meta.status !== 201){
          return this.$message.error('新增用户失败！')
        }
        this.$message.success('新增用户成功')
        // 隐藏用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    //点击确定按钮编辑用户
    editUser(){
      this.$refs.editFormRef.validate(async valid => {
        //校验失败
        if(!valid) return this.$message.error('请检查信息！')
        //可以发起编辑用户的网络请求
        const {data:res} = await this.$http.put('users/' + this.editForm.id, {
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        if(res.meta.status !== 200){
          return this.$message.error('用户信息更新失败！')
        }
        this.$message.success('用户信息更新成功！')
        // 隐藏用户对话框
        this.editDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 展示修改编辑用户信息对话框
    async showEditDialog(id){
      // 查询用户信息
      const {data:res} = await this.$http.get('users/' + id)
      if(res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      // 查询到的信息保存下来
      this.editForm = res.data
      // 显示修改用户信息对话框
      this.editDialogVisible = true
    },
    // 监听关闭编辑用户对话框关闭
    editDialogClosed(){
      // 清空验证表单信息
      this.$refs.editFormRef.resetFields()
    },
    // 根据id删除用户
    async deleteList(id){
      const data = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).catch(error => {
                return error
              })
      // 取消删除用户
      if(data !== 'confirm'){
        return this.$message.info('取消删除用户')
      }
      // 发出删除用户请求
      const {data:res} = await this.$http.delete('users/' + id)
      if(res.meta.status !== 200){
        this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      // 刷新列表
      this.getUserList()
      // 关闭对话框
      // this.editDialogVisible = true
      // console.log(res)
    },
    // 点击分配角色按钮
    async setRole(userInfo){
      // 在展示对话框之前，获取所有的角色列表
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error('获取角色信息失败！')
      }
      this.roleInfo = res.data
      this.setRolesdialogVisible = true
      this.userInfo = userInfo
      // console.log(userInfo)
    },
    // 分配角色对话框关闭时
    setRoleClosed(){
      this.roleValue = ''
    },
    // 分配新角色
    async setNewRole(){
     const {data:res} = await this.$http.put('users/' + this.userInfo.id + '/role', {
        rid : this.roleValue
      })
      if(res.meta.status !== 200){
        // console.log(res)
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('设置角色成功！')
      this.getUserList()
      this.setRolesdialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
